package com.mall.b2c.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.mall.b2c.service.StoreGoodsService;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.mall.b2c.bean.GoodsBean;
import com.mall.b2c.domain.goods.GoodsCategoryDomain;
import com.mall.b2c.domain.goods.GoodsDomain;
import com.mall.b2c.domain.member.MemberDomain;
import com.mall.b2c.plugin.search.GoodsSearchPluginBundle;
import com.mall.b2c.plugin.search.IGoodsSearchFilter;
import com.mall.b2c.plugin.search.SearchSelector;
import com.mall.b2c.service.GoodsSearchService;
import com.mall.b2c.service.GoodsService;
import com.mall.common.bean.Pager;
import com.mall.common.hibernate.Finder;
import com.mall.common.plugin.IPlugin;
import com.mall.common.util.UrlUtils;


/**
 * @author wangzx
 * Service实现类 - 商品列表(根据商品分类)
 */
@Service
@Transactional(readOnly=true)
public class GoodsSearchServiceImpl implements GoodsSearchService {
	@Resource
	private StoreGoodsService storeGoodsService;
	
	@Override
	public Map<String, Object> list(String uri, Map<String, String> paramMap, GoodsCategoryDomain goodsCategory, MemberDomain member,
			Pager pager, GoodsSearchPluginBundle goodsSearchPluginBundle) {
		Map<String, Object> result = new HashMap<String, Object>();
		Finder finder = Finder.create("select g.goods from StoreGoodsDomain g where g.goods.isMarketable=true");
		this.filterTerm(finder, paramMap, goodsCategory, uri, goodsSearchPluginBundle);
		pager = storeGoodsService.findByPager(dealPage(pager, uri), finder);
		
		List<?> goodsList = pager.getList();
		if(!CollectionUtils.isEmpty(goodsList)){
			List<GoodsBean> beans = Lists.newLinkedList();
			for(Object obj : goodsList){
				GoodsDomain goods = (GoodsDomain) obj;
				beans.add(new GoodsBean(goods, member));
			}
			pager.setList(beans);
		}
		
		result.put("pager", pager);
		result.put("selectorMap", getSelectorMap(goodsCategory, uri, finder, goodsSearchPluginBundle));
		return result;
	}
	
	private Map<String, Object> getSelectorMap(GoodsCategoryDomain goodsCategory, String url, Finder finder, GoodsSearchPluginBundle goodsSearchPluginBundle){
		String hql = StringUtils.substringBefore(StringUtils.substringAfter(finder.getOrigHql(), "from"), "order by");
		Map<String, Object> selectorMap = new HashMap<String, Object>();
		Map<String, String> paramMap = UrlUtils.getParams(url);
		List<IPlugin> filterList = goodsSearchPluginBundle.getPluginList();
		String noPageUrl = UrlUtils.getExParamUrl(url, "page");
		noPageUrl = UrlUtils.getExParamUrl(noPageUrl, "stock");
		for (IPlugin plugin : filterList) {
			IGoodsSearchFilter filter = (IGoodsSearchFilter) plugin;
			String urlFragment = UrlUtils.getParamStringValue(url, filter.getFilterId());
			String exSelfurl = UrlUtils.getExParamUrl(noPageUrl, filter.getFilterId());
			List<SearchSelector> selectorList = filter.createSelectorList(goodsCategory, exSelfurl, urlFragment, paramMap, hql, finder);
			if (selectorList != null) {
				selectorMap.put(filter.getSysId(), selectorList);
			}
		}
		return selectorMap;
	}
	
	/**
	 * 过滤搜索条件
	 */
	private void filterTerm(Finder finder, Map<String, String> paramMap, GoodsCategoryDomain cat, String url, GoodsSearchPluginBundle goodsSearchPluginBundle) {
		filterParam(finder, paramMap.get("keyword"));
		filterStoreParam(finder, paramMap.get("storeId"));
		/**
		 * 如果按类别搜索,则查询此类别,并传递给过虑器
		 * 如果未按类别搜索,则传递null                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
		 */
		List<IPlugin> filterList = goodsSearchPluginBundle.getPluginList();
		for(IPlugin iPlugin : filterList) {
			if(iPlugin instanceof IGoodsSearchFilter) {
				IGoodsSearchFilter filter = (IGoodsSearchFilter)iPlugin;
				String urlFragment = UrlUtils.getParamStringValue(url, filter.getFilterId());
				filter.filter(finder, cat, urlFragment);
			}
		}
	}
	public void filterStoreParam(Finder finder, String storeId) {
		finder.append(" and g.store.id = :storeId");
		finder.setParam("storeId", Long.valueOf(storeId));
	}

	public void filterParam(Finder finder, String keyword) {
		if(StringUtils.isNotBlank(keyword)) {
			keyword = keyword.replace("@@", "-").replace("%", "@%");
			finder.append( " and (g.goods.code like :goodsCode");//商品编号
			finder.append(" OR g.goods.pyName like :goodsPyName");//英文名称
			finder.append(" OR g.goods.name like :goodsName escape '@'");//名称
			finder.append(" OR g.goods.byName like :goodsByName escape '@'");//通用名
			//finder.append(" OR g.manufacturer like :goodsManufacturer escape '@'");//生产厂家
			finder.append(")");
			finder.setParam("goodsCode", "%"+keyword+"%");
			finder.setParam("goodsPyName", "%"+keyword+"%");
			finder.setParam("goodsName", "%"+keyword+"%");
			finder.setParam("goodsByName", "%"+keyword+"%");
			//finder.setParam("goodsManufacturer", "%"+keyword+"%");
		}
	}
	
	public Pager dealPage(Pager pager, String uri){
		String pageStr = UrlUtils.getParamStringValue(uri, "page");
		Integer page = (Integer)ConvertUtils.convert(pageStr, Integer.class);
		if(page > 1){
			pager.setPageNumber(page);
		}
		return pager;
	}

}